<?php

/*
 * this control use to manage membership, tasks in this control include:
 * 1)apply for membership
 * 2)approve membership
 * 3)assign role to customer
 * 
 */

class BUIRole extends BUIControl {

    const Show_Admin_Role = 'showAdminRole';
    const Show_Add_Role = 'showAddRole';
    const Radio_Space_Role = 'radioSpaceRole';
    const Add_Child_Role = 'addChildRole';
    const Add_SpaceRole_To_List = 'addSpaceRoleToList';
    const Delete_SpaceRole_From_List = 'deleteSpaceRoleFromList';
    const Delete_Child_Role = 'deleteChildRole';
    const Check_Space_Role = 'checkSpaceRole';

    public function onRun($data = NULL) {
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $theme = Blyn::app()->getUIManager()->getTheme();

        //below code used for adjust theme control
        $control = new BUIControl('roleControl2');
        if ($theme == BUIBlyn::Theme_Mobile_Bootstrap) {
            $control = new BUIWXControl('roleControl2');
        }

        $updateControl->addChildControl($control);

        if ($sender->isAjaxLinkClicked(self::Show_Admin_Role)) {
            $roleListData = $this->getAllSpaceRoleData(FALSE);

            $updateControl->addRenderView('adminRole', 'adminRole', array('spaceRoleData' => $roleListData));
        }

        if ($sender->isAjaxLinkClicked(self::Show_Add_Role)) {
            $parentRoleId = $activeLink->getLinkVariable('roleId');

            $updateControl->addRenderView('showAddRole', 'showAddRole', array('parentRoleId' => $parentRoleId));
        }

        if ($sender->isAjaxLinkClicked(self::Check_Space_Role)) {
            $roleListData = $this->getAllSpaceRoleData();
            $control->addRenderView('checkSpaceRole', array('spaceRoleData' => $roleListData));
        }

        if ($sender->isAjaxLinkClicked(self::Add_Child_Role)) {
            $parentRoleId = $activeLink->getLinkVariable('parentRoleId');

            $postManage = new BPostManager();
            $postData = $postManage->parsedModelData();
            $mediaList = $postManage->populateMediaListFromPostData($postData);

            $roleName = $mediaList['roleName']->content;
            $roleAlias = $mediaList['roleAlias']->content;

            $parentRole = new BRole($parentRoleId);
            $role = $parentRole->addChild($roleName);

            $this->addRoleAlias($roleAlias, $role->getFullName());

            $roleData = $this->getAllSpaceRoleData(FALSE);
            $control->addRenderView('adminRole', 'adminRole', array('spaceRoleData' => $roleData));
        }

        if ($sender->isAjaxLinkClicked(self::Add_SpaceRole_To_List)) {
            $roleId = $activeLink->getLinkVariable('roleId');
            $tableName = $activeLink->getLinkVariable('tableName');
            $tableClass = $activeLink->getLinkVariable('tableClass');
            $listId = $activeLink->getLinkVariable('listId');
            if ($tableName != NULL && $listId != NULL) {
                if ($tableClass == NULL)
                    $tableClass = 'BASheet';
                $table = new $tableClass($tableName);
                $owner = $table->getListById($listId);
            }
            $role = new BRole($roleId);
            $parentRole->addChild($roleName);
            $roleData = $this->getAllSpaceRoleData();
            $control->addRenderView('adminRole', array('spaceRoleData' => $roleData));
        }
    }

    public function onRender($data = NULL) {
        parent::onRender($data);
        if ($data == self::Check_Space_Role) {
            $roleListData = $this->getAllSpaceRoleData();
            $this->addRenderView('checkSpaceRole', array('spaceRoleData' => $roleListData));
        }
    }

    /**
     * 
     * @param type $format
     */
    public function getAllSpaceRoleData($isFormatted = TRUE) {
        $rootRole = Blyn::app()->getActiveSpace()->getSpaceEngine()->getRole(BRole::Role_App_Root);
        $memberRole = Blyn::app()->getActiveSpace()->getSpaceEngine()->getRole(BRole::Role_App_Member);
        $customerRole = Blyn::app()->getActiveSpace()->getSpaceEngine()->getRole(BRole::Role_App_customer);
        $adminRole = Blyn::app()->getActiveSpace()->getSpaceEngine()->getRole(BRole::Role_App_Admin);

        $spaceMemberRoles = array();
        $spaceMemberRoles[$memberRole->getId()] = $memberRole;
        $spaceAdminRoles = array();
        $spaceAdminRoles[$adminRole->getId()] = $adminRole;
        $spaceCustomerRoles = array();
        $spaceCustomerRoles[$customerRole->getId()] = $customerRole;

        $spaceMemberRoles += $memberRole->getChildren(NULL, TRUE);
        $spaceCustomerRoles += $customerRole->getChildren(NULL, TRUE);
        $spaceAdminRoles += $adminRole->getChildren(NULL, TRUE);
        $spaceRoles = $rootRole->getChildren(NULL, TRUE);

        if (!$isFormatted) {
            return array(
                'memberRoleData' => $spaceMemberRoles,
                'customerRoleData' => $spaceCustomerRoles,
                'adminRoleData' => $spaceAdminRoles
            );
        } else {
            $data = array();
            $adminRoleData = array();
            $memberRoleData = array();
            $customerRoleData = array();

            //first add space role into list
            $adminRoleData[$adminRole->getId()] = 'BSpaceEngine::' . $adminRole->getName();
            $memberRoleData[$memberRole->getId()] = 'BSpaceEngine::' . $memberRole->getName();
            $customerRoleData[$customerRole->getId()] = 'BSpaceEngine::' . $customerRole->getName();

            foreach ($spaceAdminRoles as $id => $role) {
                $appClass = 'BApp';
                $appId = $role->appId;
                if (is_numeric($appId) && $appId > 0) {
                    $app = BApp::getAppById($appId);
                    $appClass = get_class($app);
                }
                $adminRoleData[$id] = $appClass . '::' . $role->getName();
            }
            $data['adminRoleData'] = $adminRoleData;
            foreach ($spaceMemberRoles as $id => $role) {
                $appClass = 'BApp';
                $appId = $role->appId;
                if (is_numeric($appId) && $appId > 0) {
                    $app = BApp::getAppById($appId);
                    $appClass = get_class($app);
                }
                $memberRoleData[$id] = $appClass . '::' . $role->getName();
            }
            $data['memberRoleData'] = $memberRoleData;
            foreach ($spaceCustomerRoles as $id => $role) {
                $appClass = 'BApp';
                $appId = $role->appId;
                if (is_numeric($appId) && $appId > 0) {
                    $app = BApp::getAppById($appId);
                    $appClass = get_class($app);
                }
                $customerRoleData[$id] = $appClass . '::' . $role->getName();
            }
            $data['customerRoleData'] = $customerRoleData;

            return $data;
        }
    }

    public function getAllAppRoleData($format = 'string', $data = null) {
        $app = Blyn::app()->getActiveApp();
        $appName = $app->getName();
        $spaceConn = new BUISpaceConn();
        $relatedSpaceView = $spaceConn->getSpaceRelationshipList();
        $spaceAppRoles = array();
        $roles = $app->getRoles();
        foreach ($relatedSpaceView as $list) {
            $spaceId = $list->getItem('spaceId')->getValue();
            $space = new BSpace($spaceId);
            $spaceName = $space->getName();
            $roles += $app->getRoles(array('spaceId' => $spaceId));
        }
        foreach ($roles as $id => $role) {
            $spaceId = $role->spaceId;
            $space = new BSpace($spaceId);
            $spaceName = $space->getName();
            if ($format == 'string') {
                $spaceAppRoles[$id] = $spaceName . '|' . $appName . '::' . $this->getRoleAliasByFullName($role->getFullName());
            }
        }
        return $spaceAppRoles;
    }

    public static function getRoleAliasByFullName($roleFullName) {
        $aliasTable = new BSheet('roleAlias');
        $list = $aliasTable->getList(array('itemData' => array('roleFullName' => $roleFullName)));
        if ($list) {
            return $list->getItem('roleAlias')->getValue();
        } else {
            if (preg_match("/(app_customer)$/", $roleFullName)) {
                $aliasTable->addList(array('roleFullName' => $roleFullName, 'roleAlias' => '基本客户'));
            }
            if (preg_match("/(app_member)$/", $roleFullName)) {
                $aliasTable->addList(array('roleFullName' => $roleFullName, 'roleAlias' => '机构成员'));
            }
            if (preg_match("/(app_admin)$/", $roleFullName)) {
                $aliasTable->addList(array('roleFullName' => $roleFullName, 'roleAlias' => '系统员'));
            }
            $list = $aliasTable->getList(array('itemData' => array('roleFullName' => $roleFullName)));
        }
        //FIND AGAIN
        $list = $aliasTable->getList(array('itemData' => array('roleFullName' => $roleFullName)));
        if ($list) {
            return $list->getItem('roleAlias')->getValue();
        }
        return $roleFullName;
    }

    protected function addRoleAlias($alias, $roleFullName) {

        $roleAliasTable = new BSheet('roleAlias');

        if ($roleFullName != NULL && $alias !== NULL) {
            $list = $roleAliasTable->getNewList();
            $list->addItems(array('roleAlias' => $alias, 'roleFullName' => $roleFullName));
        }
    }

}
